package hisp_interface;

import java.io.BufferedReader;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.PrivateKey;
import javax.crypto.Cipher;
import java.io.BufferedWriter;
import java.io.Console;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.security.*;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.SSLSocket;

public class Interface {
	private SSLConnection ssl;
	private Identity identity = null;
	private BufferedReader stdin = null;
	private boolean isWork = true; 
	private HealthRecord hr = null;
	private String ip;
	private int port;


	public Interface(String ip, int port) {
		ssl = new SSLConnection(ip, port);
		this.ip = ip;
		this.port = port;
		InputStream inputstream = System.in;
		InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
		stdin = new BufferedReader(inputstreamreader);
	}

	public void run()
	{
		try {
			while (isWork) {
				if (identity == null) {
					System.out.println("\n-Health Information Service Provider-");
					System.out.println(" [please log in]");
					System.out.println(
							" 1. Log in\n" +
							" 2. create account\n" +
					" 0. Exit");
					System.out.print(">");

					String cmd = stdin.readLine();
					if (cmd.equals("0")) {
						break;
					}
					else if (cmd.equals("1") && identity == null) {
						logIn();
					}
					else if (cmd.equals("2") && identity == null) {
						createNewAccount();
					}
				}
				else if (hr == null){
					System.out.println("\n-Health Information Service Provider-");
					System.out.println(" [welcome " + identity.firstName + "]");
					System.out.println(
							" 1. load health record\n" +
							" 2. create health record\n" +
					" 0. Exit");
					System.out.print(">");

					String cmd = stdin.readLine();
					if (cmd.equals("0")) {
						ssl.writeLine(new Message().setMessage("logoff").toXml());
						break;
					}
					else if (cmd.equals("1")) {
						loadHealthRecord();
					}
					else if (cmd.equals("2")) {
						createHealthRecord();
					}
				}
				else { // we have health record now
					System.out.println("\n-Health Information Service Provider-");
					System.out.println(" welcome [" + identity.firstName + "]");
					System.out.println(" health record for [" + hr.patientId + "] loaded");
					System.out.println(
							" 1. review health record\n" +
							" 2. edit health record\n" +
							" 3. edit access control list\n" +
							" 4. append diagnosis\n" +
							" 5. append treatment\n" +
							" 6. append test result\n" +
					" 0. back");
					System.out.print(">");

					String cmd = stdin.readLine();
					if (cmd.equals("0")) {
						hr = null;
					}
					else if (cmd.equals("1")) {
						hr.printHealthRecord();
					}
					else if (cmd.equals("2")) {
						alterHealthRecord();
					}
					else if (cmd.equals("3")) {
						alterAccessControlList();
					}
					else if (cmd.equals("4")) {
						appendDiagnosis();
					}
					else if (cmd.equals("5")) {
						appendTreatment();
					}
					else if (cmd.equals("6")) {
						appendTestResult();
					}
					else {
						System.out.println("invalid input");
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void alterAccessControlList() {
		Message message;
		try {
			ssl.writeLine(new Message().setMessage("requestRole").toXml());
			message = new Message(ssl.readLine());
			if (message.getMessage().equals("accepted")) {
				message = new Message(ssl.readLine());
				if (!message.getMessage().equals("doctor")) {
					System.out.println("Only doctor has permision to create new health record.");
					return;
				}
				while(true) {
					System.out.println("\n-Health Information Service Provider-");
					System.out.println(" welcome [" + identity.firstName + "]");
					System.out.println(" health record for [" + hr.getId() + "] loaded");
					System.out.println(
							" 1. authorize new professional\n" +
							" 2. revoke authorized professional\n" +
					" 0. back");
					System.out.print(">");
					String cmd;

					cmd = stdin.readLine();
					if (cmd.equals("0")) {
						break;
					}
					else if (cmd.equals("1")) {
						authorizeNewProfessional();
					}
					else if (cmd.equals("2")) {
						revokeAuthorizedProfessional();
					}
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	private void authorizeNewProfessional() {
		try {
			ssl.writeLine(new Message().setMessage("addAccessControlList")
					.setIdentity(null, null, null, identity.getXMLString())
					.setHealthRecord(hr.getId(), null, null, null, null, null)
					.toXml());
			Message message = new Message(ssl.readLine());
			System.out.println(message.toXml());
			if (message.getMessage().equals("accepted")) {			
				message = new Message(ssl.readLine());
				System.out.println(message.toXml());
				if (message.getMessage().equals("authorized")) {
					while(true) {
						System.out.println("\n-Health Information Service Provider-");
						System.out.println(" welcome [" + identity.firstName + "]");
						System.out.println(" health record for [" + hr.getId() + "] loaded");
						System.out.println("\nenter id of new authorized doctor/nurse (doctor-writeLine/nurse-read)");
						System.out.println("type 0 to return to HR menu");
						System.out.print(">");

						String cmd = stdin.readLine();

						if (cmd.equals("0")) {
							cmd = "end";
						}
						ssl.writeLine(new Message().setMessage(cmd).toXml());
						message = new Message(ssl.readLine());

						if (message.getMessage().equals("end")) {
							break;
						}
						else if (message.getMessage().equals("failed")) {
							System.out.println("failed to find id.");
						}
						else if (message.getMessage().equals("updated")){
							System.out.println("the acl is successfully updated");
						}
					}
				}
				else if (message.getMessage().equals("denied")){
					System.out.println("you have no permition");
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	
	private void revokeAuthorizedProfessional() {
		int index;
		try {
			ssl.writeLine(new Message().setMessage("revokeAccessControlList")
					.setIdentity(null, null, null, identity.getXMLString())
					.setHealthRecord(hr.getId(), null, null, null, null, null)
					.toXml());
			Message message = new Message(ssl.readLine());
			if (message.getMessage().equals("accepted")) {	
				message = new Message(ssl.readLine());
				System.out.println("revoke = " + message.toXml());
				if (message.getMessage().equals("authorized")) {
					AccessControlList acl = new AccessControlList(message.getHealthRecordAttribute("acl"));			

					while(true) {			
						System.out.println("\n-Health Information Service Provider-");
						System.out.println(" welcome [" + identity.firstName + "]");
						System.out.println(" health record for [" + hr.getId() + "] loaded");
						System.out.println();
						acl.printUsers();
						System.out.println();
						System.out.println("\nenter index of authorized doctor/nurse to revoke");
						System.out.println("type 'q' to return to HR menu");
						System.out.print(">");

						String cmd = stdin.readLine();

						if (cmd.equals("q")) {
							break;
						}
						else {
							try {
								index = Integer.parseInt(cmd.trim());

								if (!acl.revokeUser(index)) {
									System.out.println("you cannot revoke yourself or the patient");
								}
							}
							catch (NumberFormatException e) {
								System.out.println("invalid Input");
							}
						}
					}
					System.out.println("revoked - " + acl.getXMLString());
					ssl.writeLine(new Message().setHealthRecord(null, null, null, acl.getXMLString(), null, null).toXml());
					message = new Message(ssl.readLine());

					if (message.getMessage().equals("failed")) {
						System.out.println("failed to udpate. nothing changed");
					}
					else if (message.getMessage().equals("updated")){
						System.out.println("the health record is successfullly updated");
					}

				}
				else if (message.getMessage().equals("denied")){
					System.out.println("you have no permition");
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	private void appendTestResult() {
		try {
			ssl.writeLine(new Message().setMessage("alterHealthRecord")
					.setHealthRecord(hr.getId(), null, null, null, null, null)
					.setIdentity(null, null, null, identity.getXMLString())
					.toXml());
			Message message = new Message(ssl.readLine());
			if (message.getMessage().equals("accepted")) {
				message = new Message(ssl.readLine());
				if (message.getMessage().equals("authorized")) {
					hr.addTestResult(identity, stdin);
					ssl.writeLine(new Message().setHealthRecord(identity.id, hr.toPrivateXml(), hr.toPublicXml(), null, null, null).toXml());
					message = new Message(ssl.readLine());

					if (message.getMessage().equals("failed")) {
						System.out.println("failed to append. initiates reloading process");
						loadHealthRecord(hr.getId());
					}
					else if (message.getMessage().equals("updated")){
						System.out.println("the treatment is successfullly appended to HR");
					}
				}
			}
			else if (message.getMessage().equals("denied")){
				System.out.println("you have no permition");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void appendTreatment() {
		try {
			ssl.writeLine(new Message().setMessage("alterHealthRecord")
					.setHealthRecord(hr.getId(), null, null, null, null, null)
					.setIdentity(null, null, null, identity.getXMLString())
					.toXml());
			Message message = new Message(ssl.readLine());
			if (message.getMessage().equals("accepted")) {
				message = new Message(ssl.readLine());
				if (message.getMessage().equals("authorized")) {
					hr.addTreatment(identity, stdin);
					ssl.writeLine(new Message().setHealthRecord(identity.id, hr.toPrivateXml(), hr.toPublicXml(), null, null, null).toXml());
					message = new Message(ssl.readLine());

					if (message.getMessage().equals("failed")) {
						System.out.println("failed to append. initiates reloading process");
						loadHealthRecord(hr.getId());
					}
					else if (message.getMessage().equals("updated")){
						System.out.println("the treatment is successfullly appended to HR");
					}
				}
			}
			else if (message.getMessage().equals("denied")){
				System.out.println("you have no permition");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void appendDiagnosis() {
		try {
			ssl.writeLine(new Message().setMessage("alterHealthRecord")
					.setHealthRecord(hr.getId(), null, null, null, null, null)
					.setIdentity(null, null, null, identity.getXMLString())
					.toXml());
			Message message = new Message(ssl.readLine());
			if (message.getMessage().equals("accepted")) {
				message = new Message(ssl.readLine());
				if (message.getMessage().equals("authorized")) {
					hr.addDiagnosis(identity, stdin);
					ssl.writeLine(new Message().setHealthRecord(identity.id, hr.toPrivateXml(), hr.toPublicXml(), null, null, null).toXml());
					message = new Message(ssl.readLine());

					if (message.getMessage().equals("failed")) {
						System.out.println("failed to append. initiates reloading process");
						loadHealthRecord(hr.getId());
					}
					else if (message.getMessage().equals("updated")){
						System.out.println("the treatment is successfullly appended to HR");
					}
				}
			}
			else if (message.getMessage().equals("denied")){
				System.out.println("you have no permition");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void alterHealthRecord() {
		try {
			ssl.writeLine(new Message().setMessage("alterHealthRecord")
					.setIdentity(null, null, null, identity.getXMLString())
					.setHealthRecord(hr.getId(), null, null, null, null, null)
					.toXml());
			Message message = new Message(ssl.readLine());
			if (message.getMessage().equals("accepted")) {

				message = new Message(ssl.readLine());
				if (message.getMessage().equals("authorized")) {
					while(true) {
						System.out.println("\n-Health Information Service Provider-");
						System.out.println(" welcome [" + identity.firstName + "]");
						System.out.println(" health record for [" + hr.getId() + "] loaded");
						System.out.println(
								" 1. edit patient information\n" +
								" 2. edit guardian information\n" +
								" 3. edit primary doctor information\n" +
						" 0. back");
						System.out.print(">");

						String cmd;

						cmd = stdin.readLine();

						if (cmd.equals("0")) {
							break;
						}
						else if (cmd.equals("1")) {
							hr.patientUpdate(identity, stdin);
						}
						else if (cmd.equals("2")) {
							hr.guardianUpdate(identity, stdin);
						}
						else if (cmd.equals("3")) {
							hr.pdUpdate(identity, stdin);
						}
						else {
							System.out.println("invalid input");
							continue;							
						}
						
						ssl.writeLine(new Message().setHealthRecord(identity.id, hr.toPrivateXml(), hr.toPublicXml(), null, null, null).toXml());
						message = new Message(ssl.readLine());
						
						if (message.getMessage().equals("failed")) {
							System.out.println("failed to udpate. initiates reloading process");
							loadHealthRecord(hr.getId());
						}
						else if (message.getMessage().equals("updated")){
							System.out.println("the health record is successfullly updated");
						}
					}
				}
				else if (message.getMessage().equals("denied")){
					System.out.println("you have no permition");
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public boolean logIn() {
		String id;
		String pass;

		try {
			ssl.connect();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("check your internet connection or HISP agent is currently unavailable");
			return false;
		}

		try {
			System.out.print("Id: ");
			id = stdin.readLine();

			if (System.console() == null) {
				System.out.print("Password: ");
				pass = stdin.readLine();
			}
			else {
				pass = new String(System.console().readPassword("Password: "));
			}			
			
			ssl.writeLine(new Message().setMessage("logIn")
									.setIdentity(id, pass, null, null).toXml());
			
			Message message = new Message(ssl.readLine());

			if (message.getMessage().equals("authorized")) {
				identity = new Identity(message.getIdentityAttribute("xml"));
			}
			else {
				ssl.close();
			}
			//TODO Login
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	public void createNewAccount() {
		identity = new Identity();

		try {
			ssl.connect();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println("check your internet connection or HISP agent is currently unavailable");
			return;
		}

		try {
			System.out.print("\n-Create New Account-\n");
			System.out.println("please enter your email address (this will be your id, max 50 characters).");
			System.out.print(">");
			identity.id = stdin.readLine();

			System.out.println("please enter your first name.");
			System.out.print(">");
			identity.firstName = stdin.readLine();

			System.out.println("please enter your last name.");
			System.out.print(">");
			identity.lastName = stdin.readLine();

			String password;
			while (true) {
				System.out.println("please enter your password");
				if (System.console() == null) {
					System.out.print(">");
					password = stdin.readLine();
				}
				else {
					password = new String(System.console().readPassword(">"));
				}
				
				System.out.println(password);
				if (password.length() >= 8) {
					System.out.println("please confirm your password.");
					if (System.console() == null) {
						System.out.print(">");
						if (password.equals(stdin.readLine())) break;
						else {
							System.out.println("the passwords does not match.");
						}
					}
					else {
						if (password.equals(new String(System.console().readPassword(">")))) break;
						else {
							System.out.println("the passwords does not match.");
						}
					}

					//TODO add more constraints to have more secure password
					System.out.println(password.length());
				}
				else {
					System.out.println("your password is too short");
				}
			}


			while (!(identity.role.equals("doctor") || identity.role.equals("nurse"))) {
				System.out.println("please enter your role (doctor/nurse)");
				System.out.print(">");
				identity.role = stdin.readLine();
			}

			System.out.println("please enter your department");
			System.out.print(">");
			identity.department = stdin.readLine();

			System.out.println("please enter your organization");
			System.out.print(">");
			identity.organization = stdin.readLine();			


			String xml = identity.getXMLString();

			// hash password
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			byte[] bSalt = new byte[8];
			random.nextBytes(bSalt);

			String hashedPassword = bytes2String(getHash(password, bSalt));
			String sSalt = bytes2String(bSalt);

			ssl.writeLine(new Message().setMessage("newAccount")
							.setIdentity(identity.id, hashedPassword, sSalt, xml).toXml());
			
			Message message = new Message(ssl.readLine());
			if (message.getMessage().equals("created")) {
				System.out.println("your account is created");
			}
			else {
				System.out.println("account creation failed, the same id exists");
				identity = null;
				ssl.close();
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String createPatientAccount() {
		Identity patient = new Identity();

		try {
			System.out.print("\n-Create new patient account-\n");
			System.out.println("please enter the patient's email address (this will be your id, max 50 characters).");
			System.out.print(">");
			patient.id = stdin.readLine();

			System.out.println("please enter the patient's first name.");
			System.out.print(">");
			patient.firstName = stdin.readLine();

			System.out.println("please enter the patient's last name.");
			System.out.print(">");
			patient.lastName = stdin.readLine();

			String password;
			while (true) {
				System.out.println("please enter patient's password");
				if (System.console() == null) {
					System.out.print(">");
					password = stdin.readLine();
				}
				else {
					password = new String(System.console().readPassword(">"));
				}
				System.out.println(password);
				if (password.length() >= 8) {
					System.out.println("please confirm the patient password.");
					if (System.console() == null) {
						System.out.print(">");
						if (password.equals(stdin.readLine())) break;
						else {
							System.out.println("the passwords does not match.");
						}
					}
					else {
						if (password.equals(new String(System.console().readPassword(">")))) break;
						else {
							System.out.println("the passwords does not match.");
						}
					}

					//TODO add more constraints to have more secure password
					System.out.println(password.length());
				}
				else {
					System.out.println("your password is too short");
				}
			}

			patient.role = "patient";
			patient.department = "";
			patient.organization = "";

			String xml = patient.getXMLString();

			// hash password
			SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
			byte[] bSalt = new byte[8];
			random.nextBytes(bSalt);

			String hashedPassword = bytes2String(getHash(password, bSalt));
			String sSalt = bytes2String(bSalt);

			ssl.writeLine(new Message().setMessage("newAccount").setIdentity(patient.id, hashedPassword, sSalt, xml).toXml());
			
			Message message = new Message(ssl.readLine());
			
			if (message.getMessage().equals("failed")) {
				System.out.println("creation failed. the id already exists");
				return null;
			}
			if (message.getMessage().equals("created")) return patient.id;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}


	public void loadHealthRecord() {

		try {
			System.out.print("enter patient id of the requested health record.\n>");
			String requestId = stdin.readLine();
			ssl.writeLine(new Message().setMessage("requestHealthRecord")
					.setIdentity(null, null, null, identity.getXMLString())
					.setHealthRecord(requestId, null, null, null, null, null)
					.toXml());

			Message message = new Message(ssl.readLine());
			if (message.getMessage().equals("accepted")) {
				if ((message = new Message(ssl.readLine())).getMessage().equals("authorized")) {
					System.out.println(message.toXml());
					hr = new HealthRecord(requestId, message.getHealthRecordAttribute("identifier"), message.getHealthRecordAttribute("private"), message.getHealthRecordAttribute("public"));
				}
				else if (message.getMessage().equals("denied")){
					System.out.println("you have no access.");
				}
				else {
					System.out.println("there is no record.");
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void loadHealthRecord(String requestId) {
		System.out.println("loading health report for " + requestId);
		try {
			ssl.writeLine(new Message().setMessage("requestHealthRecord")
					.setIdentity(null, null, null, identity.getXMLString())
					.setHealthRecord(requestId, null, null, null, null, null)
					.toXml());
			Message message = new Message(ssl.readLine());
			
			if (message.equals("accepted")) {
			
				if ((message = new Message(ssl.readLine())).getMessage().equals("authorized")) {
					hr = new HealthRecord(requestId, message.getHealthRecordAttribute("identifier"), message.getHealthRecordAttribute("private"), message.getHealthRecordAttribute("public"));
				}
				else if (message.getMessage().equals("denied")){
					System.out.println("you have no access.");
				}
				else {
					System.out.println("there is no record.");
				}
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void createHealthRecord() {
		String patientId;
		Message message;
		try {
			ssl.writeLine(new Message().setMessage("requestRole").toXml());
			message = new Message(ssl.readLine());
			if (message.getMessage().equals("accepted")) {
				message = new Message(ssl.readLine());
				System.out.println("your role is " + message.getMessage());
				if (!message.getMessage().equals("doctor")) {
					System.out.println("Only doctor has permision to create new health record.");
					return;
				}				
			}
			else return;
			ssl.writeLine(new Message().setMessage("createHealthRecord").toXml());
			message = new Message(ssl.readLine());
			System.out.println(message.toXml());
			if (message.getMessage().equals("accepted")) {
				message = new Message(ssl.readLine());
				System.out.println(message.toXml());
				if (message.getMessage().equals("authorized")) {
					
					while ((patientId = createPatientAccount()) == null);
					
					hr = new HealthRecord(patientId, null);
					hr.patientUpdate(identity, stdin);
					hr.guardianUpdate(identity, stdin);
					hr.pdUpdate(identity, stdin);
						
					ssl.writeLine(new Message().setHealthRecord(hr.getId(), hr.toPrivateXml(), hr.toPublicXml() , null, null, null).toXml());
					
					message = new Message(ssl.readLine());
					if (message.getMessage().equals("created"))
						System.out.println("health record is successfully created");
					else {
						System.out.println("duplication of health record. creation failed");
						hr = null;
					}
				}
				else {
					ssl.close();
					isWork = false;
					System.out.println("server denied");
				}
				
			}
			else {
				ssl.close();
				isWork =false;
				System.out.println("server doesnot recognize you");
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private byte[] getHash(String string, byte[] salt) {		
		MessageDigest mda;
		try {
			mda = MessageDigest.getInstance("SHA-512");
			mda.reset();
			mda.update(salt);
			byte[] digest = mda.digest(string.getBytes());
			for (int i = 0; i < 1000; i++) {
				mda.reset();
				digest = mda.digest(digest);
			}

			return digest;

		} catch (NoSuchAlgorithmException e) {
			return null;
		} 
	}

	/*
	 * http://stackoverflow.com/questions/521101/using-sha1-and-rsa-with-java-security-signature-vs-messagedigest-and-cipher
	 */
	private String bytes2String(byte[] bytes) {
		StringBuilder string = new StringBuilder();
		for (byte b: bytes) {
			String hexString = Integer.toHexString(0x00FF & b);
			string.append(hexString.length() == 1 ? "0" + hexString : hexString);
		}
		return string.toString();
	}

	/*
	 * http://stackoverflow.com/questions/140131/convert-a-string-representation-of-a-hex-dump-to-a-byte-array-using-java
	 */
	public static byte[] string2Bytes(String s) {
		int len = s.length();
		byte[] data = new byte[len / 2];
		for (int i = 0; i < len; i += 2) {
			data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
					+ Character.digit(s.charAt(i+1), 16));
		}
		return data;
	}

	public String encrypt (String data, String key) {
		byte[] bKey = string2Bytes(key);
		SecretKeySpec skeySpec = new SecretKeySpec(bKey, "AES");

		Cipher cipher;
		try {
			cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

			byte[] encrpyted = cipher.doFinal(data.getBytes());

			return bytes2String(encrpyted);


		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;		
	}

	public String decrypt (String data, String key) {
		byte[] bKey = string2Bytes(key);
		SecretKeySpec skeySpec = new SecretKeySpec(bKey, "AES");

		Cipher cipher;
		try {
			cipher = Cipher.getInstance("AES");
			cipher.init(Cipher.DECRYPT_MODE, skeySpec);

			byte[] encrpyted = cipher.doFinal(data.getBytes());

			return bytes2String(encrpyted);


		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;		
	}
}
